//
//  LROAuthViewController.swift
//  LRWeibo
//
//  Created by admin on 15/9/22.
//  Copyright © 2015年 懒人. All rights reserved.
//QQ http://wiki.connect.qq.com/oauth2-0%E7%AE%80%E4%BB%8B

import UIKit
import SVProgressHUD

class LROAuthViewController: UIViewController,UIWebViewDelegate {
    
    override func loadView() {
        super.loadView()
        
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        title = "新浪微博授权登录"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "autoFill")
        
        webView.loadRequest(NSURLRequest(URL: NSURL(string: urlStr)!))
        webView.delegate = self
    }
    /// 返回
    @objc private func close()
    {
        self.navigationController?.dismissViewControllerAnimated(true, completion: nil)
        SVProgressHUD.dismiss()
    }
    
    /// 调试自动填充
    @objc private func autoFill()
    {
        let js = "document.getElementById('userId').value = 'liguohui_1@163.com';" +
        "document.getElementById('passwd').value = 'ljb7737512';"
        
        webView.stringByEvaluatingJavaScriptFromString(js)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

     // MARK: - 控件懒加载
    private lazy var webView: UIWebView = UIWebView()
    
     // MARK: - webview 代理
    func webViewDidStartLoad(webView: UIWebView) {

        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {

        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {

        SVProgressHUD.showErrorWithStatus("网络不给力")
    }
    
    // 获取code
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        if let query = request.URL?.query where query.hasPrefix("code=")
        {
            let code = query.substringFromIndex("code=".endIndex)

            // TODO: - 使用请求码获取 token
            // 组装请求体
            let prams = ["client_id": client_id,"client_secret": client_secret,"grant_type": grant_type,"code": code,"redirect_uri": redirect_uri]
            
            // 拿到token
            NetworkTool.shareNetTool.request(NetworkTool.requestMethod.POST, URLString:  token_url, prams: prams, finshBlock: { (result, error) -> () in
                
                // 获取用户信息
               let user = LRUserAccount(dict: result as! [String : AnyObject])
                
                // 组装请求体
                let prams = ["access_token": user.access_token!,"uid": user.uid!]
                
                NetworkTool.shareNetTool.request(NetworkTool.requestMethod.GET, URLString: getUser_url, prams: prams, finshBlock: { (result, error) -> () in
                    user.screen_name = result!["screen_name"] as? String
                    user.avatar_large = result!["avatar_large"] as? String
                    
                    // 保存数据到沙盒
                    NSKeyedArchiver.archiveRootObject(user, toFile: UserAccountViewModel.sharedUserAccount.savePath!)
                    
                    // 授权成功返回欢迎页面
                    NSNotificationCenter.defaultCenter().postNotificationName(LRRootViewControllChange, object: nil)
                })
            })

        }

        // 阻止返回百度页面
        if request.URL!.absoluteString.hasPrefix(redirect_uri)
        {
            return false
        }

        return true
    }

}

